package ee.graphicscard.controller;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;

import ee.graphicscard.model.dao.GraphicsCardDAO;
import ee.graphicscard.model.dao.GraphicsCardDAOImpl;
import ee.graphicscard.model.dto.GraphicsCard;

public class GraphicsCardService extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
	
	private static final Logger logger = Logger.getLogger(GraphicsCardService.class);
	
    
	@Override
	public void init()
	{
		logger.debug("I was initialized.");
	}
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException 
	{
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		GraphicsCard curGraphicsCard = retrieveGraphicsCard(request);
		Gson JSONFormatter = new Gson(); 
		JSONFormatter.toJson(curGraphicsCard, response.getWriter());
    }
    
	private GraphicsCard retrieveGraphicsCard(HttpServletRequest request)
	{
		GraphicsCard graphicsCardRetrieved = null;
		
		Integer graphicscard_id = parseInt(request.getParameter("id"));		
		if(graphicscard_id != null)
		{
			GraphicsCardDAO graphicsCardDAOImpl = new GraphicsCardDAOImpl();
			graphicsCardRetrieved = graphicsCardDAOImpl.findById(graphicscard_id);
		}
		else
		{
			logger.info("retrieveSpecies(): Could not parse the species_id provided by the client!");
		}	
		return graphicsCardRetrieved;
	}    

    @Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException 
	{
		doGet(request, response);
	}
	
	@Override
	public void destroy()
	{
		logger.debug("I was destroyed.");
	}
	
	public static Integer parseInt(String intInStringFormat)
	{
		try
		{
			Integer parsedResult = Integer.valueOf(intInStringFormat);
			return parsedResult;
		}
		catch(NumberFormatException e)
		{
			return null;
		}
	}
}